#pragma once
#include <string>
#include <cstdio>
#include <set>
#include "Command.hpp"
#include "InetAddr.hpp"
#include "Log.hpp"
using namespace std;
using namespace LogModule;

class Command
{
public:
    Command()
    {
        _whiteListCommands.insert("ls");
        _whiteListCommands.insert("pwd");
        _whiteListCommands.insert("ls -l");
        _whiteListCommands.insert("touch haha.txt");
        _whiteListCommands.insert("who");
        _whiteListCommands.insert("whiami");
    }
    bool Issafecommand(const string& cmd)//判断命令是否存在_whiteListCommands中
    {
        auto iter =_whiteListCommands.find(cmd);
        return iter != _whiteListCommands.end();
    }
    string Execute(const string& cmd,InetAddr& addr)
    {
        if(!Issafecommand(cmd))
        {
            return string("坏人");
        }
        string who=addr.StringAddr();
        FILE* fp=popen(cmd.c_str(),"r");//读取命令输出
        if(fp==nullptr)
        {
            return string("你要执行的命令不存在:")+cmd;
        }
        string res;
        char line[1024];
        while(fgets(line,sizeof(line),fp))
        {
            res+=line;
        }
        pclose(fp);
        string result=who+"execute done,result is:\n"+res;
        LOG(LogLevel::DEBUG)<<result;
        return result;
    }
private:
    set<string> _whiteListCommands;
};